package com.vcredit.creditcat.service.product.lrh;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.bird.enumtype.BankEnum;
import com.vcredit.creditcat.enumtype.AuthItemEnum;
import com.vcredit.creditcat.enumtype.LrhAuthEducationEnum;
import com.vcredit.creditcat.enumtype.LrhAuthMarriageEnum;
import com.vcredit.creditcat.enumtype.LrhProfessionTypeEnum;
import com.vcredit.creditcat.enumtype.SmsDescEnum;
import com.vcredit.creditcat.enumtype.auth.SupplementItemEnum;
import com.vcredit.creditcat.manager.SMSMessageManager;
import com.vcredit.creditcat.model.AuthPersonalAddress;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.model.CustAccount;
import com.vcredit.creditcat.model.CustProductApply;
import com.vcredit.creditcat.model.CustSupplementItem;
import com.vcredit.creditcat.model.base.AbstractItem;
import com.vcredit.creditcat.service.AuthPersonalAddressService;
import com.vcredit.creditcat.service.product.IProductApplyNewService;
import com.vcredit.creditcat.service.product.shared.ProductApplyServiceAdaptor;
import com.vcredit.creditcat.util.RSAUtil;
import com.vcredit.creditcat.util.Utility;
import com.vcredit.creditcat.vo.ProductApplyResultVo;
import com.vcredit.creditcat.vo.auth.AuthIdentityExt;
import com.vcredit.creditcat.vo.auth.AuthMobileExt;
import com.vcredit.creditcat.vo.auth.AuthPersonalInfoExt;
import com.vcredit.creditcat.vo.auth.CreditAssureExt;
import com.vcredit.creditcat.vo.auth.CustCardExt;
import com.vcredit.creditcat.vo.product.lrh.BaseInfo;
import com.vcredit.creditcat.vo.product.lrh.CheckSubmit;
import com.vcredit.creditcat.vo.product.lrh.CreditInfo;
import com.vcredit.creditcat.vo.product.lrh.IdAuthInfo;
import com.vcredit.creditcat.vo.product.lrh.LrhGetCheck;
import com.vcredit.creditcat.vo.product.lrh.LrhGetPost;
import com.vcredit.creditcat.vo.product.lrh.PostInfo;
import com.vcredit.creditcat.vo.product.lrh.SearchAmount;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.HttpRequest;
import com.vcredit.framework.util.JacksonUtil;

/**
 * 丽人荟申请实现类
 * 
 * @author zhaoqi01
 *
 */
@Service(ProductApplyServiceAdaptor.BEANNAME_PREFIX + 36)
public class LrhApplyServiceImpl implements IProductApplyNewService {

	// 审核结果 0：已审批-失败；1：已审批-成功；2：审批中；3：未申请过；
	// 4：未申请过，认证条件齐全；5：额度获取失败临时状态

	@Value("${xinyongmao.publicKey}")
	private String publicKey;

	@Value("${product.lrh.url}")
	private String url;

	@Value("${product.lrh.appkey}")
	private String appKey;

	@Value("${product.lrh.appSecret}")
	private String appSecret;

	@Value("${resource.soft.url}")
	private String imagUrl;

	@Autowired
	private AuthPersonalAddressService authPersonalAddressService;

	@Autowired
	public SMSMessageManager sMSMessageManager;

	private static Logger logger = LoggerFactory.getLogger(LrhApplyServiceImpl.class);

	private String source = "XINYONGMAO";
	private String lrhCheck = "/isCanDecision";
	private String lrhPost = "/applyDecision";
	private String lrhSearch = "/queryDecision";
	private String version = "1.0";

	@Log
	@Override
	public ProductApplyResultVo apply(Map<Integer, AbstractItem> custAuthInfoMap,
			Map<Long, CustSupplementItem> custSupplementItemMap, Map<String, Object> otherParams) {

		// 返回对象

		try {

			Cust cust = (Cust) otherParams.get("cust");
			CustAccount custAccount = (CustAccount) otherParams.get("custAccount");

			String mobile = custAccount.getUserName();
			String idNo = custAccount.getAccountIdno();

			// 查询额度(校验异常情况下，对方是否已收到并处理过了)
			ProductApplyResultVo searchResult = searchApprovalAmount(mobile, idNo);
			if (searchResult.getCode() == 1) {
				return searchResult;
			}

			// 基本信息
			CustSupplementItem supplement = custSupplementItemMap.get(SupplementItemEnum.LRH_BASE_INFO.getItemId());
			AuthPersonalInfoExt persionInfo = JacksonUtil.Json2Obj(supplement.getDataEntity(),
					new TypeReference<AuthPersonalInfoExt>() {
					});
			// 身份认证
			// AuthIdentityExt authIdentity = (AuthIdentityExt)
			// custAuthInfoMap.get(AuthItemEnum.IDENTITY_REAL);
			// ---人脸识别
			AuthIdentityExt authIdentity2 = (AuthIdentityExt) custAuthInfoMap
					.get(AuthItemEnum.VERIFY_FACE_PAIR.getCode());
			// ---手机认证
			AuthMobileExt authMobile = (AuthMobileExt) custAuthInfoMap.get(AuthItemEnum.MOBILE.getCode());
			// ---银行卡认证
			CustCardExt custCard = (CustCardExt) custAuthInfoMap.get(AuthItemEnum.DEBIT_CARD.getCode());
			// ---合规、征信、授权
			CreditAssureExt creditAssure = (CreditAssureExt) custAuthInfoMap.get(AuthItemEnum.FOREIGN_CREDIT.getCode());

			// 调用预检接口
			// ------校验可否交单
			ProductApplyResultVo resultCheck = new ProductApplyResultVo();
			resultCheck = checkCredit(authIdentity2.getName(), idNo, authIdentity2.getLiveCompareValue().toString());
			if (resultCheck.getCustProductApply().getAuditResult() == 0) {
				return resultCheck;
			}

			// 整合需要提交的资料
			PostInfo postInfo = new PostInfo();
			// 基本资料
			BaseInfo baseInfo = new BaseInfo();
			baseInfo.setEducation(LrhAuthEducationEnum.getLrhCodeByDesc(persionInfo.getEducationKey()));
			baseInfo.setMarriage(LrhAuthMarriageEnum.getLrhCodeByDesc(persionInfo.getMarriageKey()));
			baseInfo.setIndustry(persionInfo.getIndustryValue());// #所属行业
			baseInfo.setProfession(LrhProfessionTypeEnum.getLrhCodeByDesc(persionInfo.getProfessionKey()));
			baseInfo.setSalary(persionInfo.getSalaryKey().toString());
			// --获取居住地地址
			List<AuthPersonalAddress> list = authPersonalAddressService.findByCustId(persionInfo.getCustId(), 2);
			if (null == list || list.size() == 0) {
				ProductApplyResultVo resultRe = new ProductApplyResultVo();
				CustProductApply custProductApply = new CustProductApply();
				custProductApply.setAuditResult(0);
				custProductApply.setRejectMsg("现居住地址不能为空");
				custProductApply.setIsApply(true);
				resultRe.setCode(1);
				resultRe.setCustProductApply(custProductApply);
				return resultRe;
			}
			AuthPersonalAddress authPersonalAddress = list.get(0);
			baseInfo.setLiveCity(authPersonalAddress.getCityCode());
			baseInfo.setLiveCityName(authPersonalAddress.getCity());
			baseInfo.setMobileAddr("");
			baseInfo.setCustomerName(authIdentity2.getName());

			// 身份证信息
			IdAuthInfo idAuthInfo = new IdAuthInfo();
			idAuthInfo.setIdcardNo(authIdentity2.getCitizenId());
			idAuthInfo.setHouseholdAddr(authIdentity2.getAddress());
			logger.info("========>地址转换:" + imagUrl + "\\/" + authIdentity2.getIdFront() + "#"
					+ GetImageStrFromUrl(imagUrl + "/" + authIdentity2.getIdFront()));
			idAuthInfo.setIdcardFrontBase64(GetImageStrFromUrl(imagUrl + "/" + authIdentity2.getIdFront()));
			logger.info("========>地址转换:" + imagUrl + "\\/" + authIdentity2.getIdBack() + "#"
					+ GetImageStrFromUrl(imagUrl + "/" + authIdentity2.getIdFront()));
			idAuthInfo.setIdcardBackBase64(GetImageStrFromUrl(imagUrl + "/" + authIdentity2.getIdBack()));
			// ---人脸识别
			logger.info("========>地址转换:" + imagUrl + "\\/" + authIdentity2.getIdFace() + "#"
					+ GetImageStrFromUrl(imagUrl + "/" + authIdentity2.getIdFace()));
			idAuthInfo.setFaceBase64(GetImageStrFromUrl(imagUrl + "/" + authIdentity2.getIdFace()));
			idAuthInfo.setFaceRecognitionScore(authIdentity2.getLiveCompareValue().toString());
			// ---手机认证

			// 手机认证
			if (null == custSupplementItemMap.get(SupplementItemEnum.HL_MOBILE.getItemId())) {
				idAuthInfo.setMobileBillId(authMobile.getMobileId());// 手机账单id
				idAuthInfo.setIdAuthMobile(authMobile.getMobile());// 手机认证时的手机号码
			} else {
				AuthMobileExt mobileBCRZX = JacksonUtil.Json2Obj(
						custSupplementItemMap.get(SupplementItemEnum.HL_MOBILE.getItemId()).getDataEntity(),
						new TypeReference<AuthMobileExt>() {
						});
				idAuthInfo.setMobileBillId(mobileBCRZX.getMobileId());// 手机账单id
				idAuthInfo.setIdAuthMobile(mobileBCRZX.getMobile());// 手机认证时的手机号码
			}

			// 银行卡信息 //借记卡或贷记卡
			CreditInfo creditInfo = new CreditInfo();
			String cardType = custCard.getCardType().toString();
			if (cardType.equals("1")) {
				cardType = "借记卡";
			} else {
				cardType = "非借记卡";
			}
			creditInfo.setBankCardType(cardType);// 验卡银行卡类型
			creditInfo.setBankCardNo(custCard.getAccountNo().toString());// 银行卡
			creditInfo.setBankCardName(BankEnum.getDescByCode(custCard.getBankCode()));
			creditInfo.setBankCardCode(BankEnum.getVbsByCode(custCard.getBankCode()));
			creditInfo.setReservedMobile(custCard.getReservedMobile());
			// ---合规、征信、授权
			logger.info("========>地址转换:" + imagUrl + "\\/" + creditAssure.getSignatureImg() + "#"
					+ GetImageStrFromUrl(imagUrl + "/" + creditAssure.getSignatureImg()));
			creditInfo.setSignBase64(GetImageStrFromUrl(imagUrl + "/" + creditAssure.getSignatureImg()));// 授权图片
			creditInfo.setComplianceApplyId(creditAssure.getApplyId().toString());// 合规ID
			creditInfo.setCreditReportId(creditAssure.getReportId().toString());// 征信ID

			// 合并
			postInfo.setCaller(source);
			postInfo.setVersion("1.0");
			postInfo.setAppKey(appKey);
			postInfo.setUserAccount(mobile);

			// 生成密码 并加密
			String pwd = Utility.getRandom(8).toString();
			String pwdSubmit = pwd;
			byte[] data = pwdSubmit.getBytes();
			byte[] encodedData = RSAUtil.encryptByPublicKey(data, publicKey);
			pwdSubmit = new String(Base64.encodeBase64(encodedData));

			logger.info("========>丽人荟账号密码#" + mobile + "#" + pwd);
			pwd = Utility.md5(pwd);
			pwd = pwd.toUpperCase();

			postInfo.setPassword(pwd);
			postInfo.setSaleId("");
			postInfo.setIdAuthInfo(idAuthInfo);
			postInfo.setCreditInfo(creditInfo);
			postInfo.setBaseInfo(baseInfo);

			// 提交信息到丽人荟
			ProductApplyResultVo result = new ProductApplyResultVo();
			result = submitInfo(postInfo, pwdSubmit, custAccount);

			return result;
		} catch (Exception ex) {
			ProductApplyResultVo result = new ProductApplyResultVo();
			logger.error("========>丽人荟申请出现异常:", ex);
			result.setCode(0);
			result.setMsg(ex.getMessage());
			return result;
		}
	}

	public static String GetImageStrFromUrl(String imgURL) {
		byte[] data = null;
		try {
			// 创建URL
			URL url = new URL(imgURL);
			// 创建链接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(30 * 1000);
			InputStream inStream = conn.getInputStream();

			ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
			byte[] buff = new byte[100];
			int rc = 0;
			while ((rc = inStream.read(buff, 0, 100)) > 0) {
				swapStream.write(buff, 0, rc);
			}
			data = swapStream.toByteArray();

			inStream.read(data);
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 返回Base64编码过的字节数组字符串
		return Base64.encodeBase64String(data);
	}

	/**
	 * 校验可否交单(撞库)
	 * 
	 * @param customerName
	 * @return
	 */
	@Log
	public ProductApplyResultVo checkCredit(String customerName, String idcardNo, String faceRecognitionScore)
			throws Exception {

		ProductApplyResultVo rs = new ProductApplyResultVo();

		// 生成签名
		String sign = "";// 签名串
		TreeMap<String, String> parameterMap = new TreeMap<String, String>();
		parameterMap.put("caller", source);
		parameterMap.put("version", "1.0");
		parameterMap.put("appKey", appKey);
		parameterMap.put("customerName", customerName);
		parameterMap.put("idcardNo", idcardNo);
		parameterMap.put("faceRecognitionScore", faceRecognitionScore);

		sign = createSign(appSecret, parameterMap);

		// 组装提交参数
		CheckSubmit checkSubmit = new CheckSubmit();
		checkSubmit.setCaller(source);
		checkSubmit.setVersion(version);
		checkSubmit.setAppKey(appKey);
		checkSubmit.setSign(sign);
		checkSubmit.setCustomerName(customerName);
		checkSubmit.setIdcardNo(idcardNo);
		checkSubmit.setFaceRecognitionScore(faceRecognitionScore);

		// lrh返回
		String submitJason = JacksonUtil.Obj2Json(checkSubmit);
		logger.info("lrh:" + lrhCheck + "#" + submitJason);
		String resultJson = HttpRequest.doJson(url + lrhCheck, submitJason, 30);
		LrhGetCheck result = JacksonUtil.Json2Obj(resultJson, new TypeReference<LrhGetCheck>() {
		});
		logger.info("lrh:" + lrhCheck + "#" + JacksonUtil.Obj2Json(result));

		if (result.getStatus() == 1) {
			CustProductApply custProductApply = new CustProductApply();
			custProductApply.setAuditResult(1);
			custProductApply.setRejectMsg(result.getMessage());
			rs.setCode(1);
			rs.setMsg(result.getMessage());
			rs.setCustProductApply(custProductApply);
		} else {
			rs.setCode(1);
			CustProductApply custProductApply = new CustProductApply();
			custProductApply.setAuditResult(0);
			custProductApply.setRejectMsg(result.getMessage());
			custProductApply.setIsApply(false);

			rs.setCustProductApply(custProductApply);
		}
		return rs;
	}

	/**
	 * 提交到丽人荟
	 * 
	 * @return @throws Exception @throws
	 */
	@Log
	public ProductApplyResultVo submitInfo(PostInfo postInfo, String pwdSubmit, CustAccount custAccount)
			throws Exception {

		ProductApplyResultVo rs = new ProductApplyResultVo();

		// 生成签名
		String sign = "";// 签名串
		TreeMap<String, Object> parameterMap = new TreeMap<String, Object>();
		parameterMap.put("caller", postInfo.getCaller());
		parameterMap.put("version", postInfo.getVersion());
		parameterMap.put("appKey", postInfo.getAppKey());
		parameterMap.put("userAccount", postInfo.getUserAccount());
		parameterMap.put("password", postInfo.getPassword());
		parameterMap.put("saleId", postInfo.getSaleId());
		// BaseInfo
		parameterMap.put("education", postInfo.getBaseInfo().getEducation());
		parameterMap.put("marriage", postInfo.getBaseInfo().getMarriage());
		parameterMap.put("industry", postInfo.getBaseInfo().getIndustry());
		parameterMap.put("profession", postInfo.getBaseInfo().getProfession());

		String key = postInfo.getBaseInfo().getSalary();
		String salary = "1000";

		switch (Integer.parseInt(key)) {
		case 1:
			salary = "1000";
			break;
		case 2:
			salary = "2000";
			break;
		case 3:
			salary = "4000";
			break;
		case 4:
			salary = "6000";
			break;
		case 5:
			salary = "8000";
			break;
		case 6:
			salary = "10000";
			break;
		case 7:
			salary = "12000";
			break;
		case 8:
			salary = "15000";
			break;
		case 9:
			salary = "20000";
			break;
		case 10:
			salary = "25000";
			break;
		default:
			break;
		}
		// salary="10";//测试
		parameterMap.put("salary", salary);
		postInfo.getBaseInfo().setSalary(salary);
		parameterMap.put("liveCity", postInfo.getBaseInfo().getLiveCity());
		parameterMap.put("liveCityName", postInfo.getBaseInfo().getLiveCityName());
		parameterMap.put("mobileAddr", postInfo.getBaseInfo().getMobileAddr());
		parameterMap.put("customerName", postInfo.getBaseInfo().getCustomerName());
		// IdAuthInfo
		parameterMap.put("idcardNo", postInfo.getIdAuthInfo().getIdcardNo());
		parameterMap.put("householdAddr", postInfo.getIdAuthInfo().getHouseholdAddr());
		parameterMap.put("faceRecognitionScore", postInfo.getIdAuthInfo().getFaceRecognitionScore());
		parameterMap.put("mobileBillId", postInfo.getIdAuthInfo().getMobileBillId());
		parameterMap.put("idAuthMobile", postInfo.getIdAuthInfo().getIdAuthMobile());
		// CreditInfo
		parameterMap.put("bankCardType", postInfo.getCreditInfo().getBankCardType());
		parameterMap.put("bankCardNo", postInfo.getCreditInfo().getBankCardNo());

		parameterMap.put("bankCardName", postInfo.getCreditInfo().getBankCardName());
		parameterMap.put("bankCardCode", postInfo.getCreditInfo().getBankCardCode());
		parameterMap.put("reservedMobile", postInfo.getCreditInfo().getReservedMobile());
		parameterMap.put("complianceApplyId", postInfo.getCreditInfo().getComplianceApplyId());
		parameterMap.put("creditReportId", postInfo.getCreditInfo().getCreditReportId());
		sign = createSign(appSecret, parameterMap);

		// 加入签名
		postInfo.setSign(sign);

		// lrh返回
		String submitJason = JacksonUtil.Obj2Json(postInfo);
		logger.info("lrh:" + lrhPost + "#" + submitJason);
		String resultJson = HttpRequest.doJson(url + lrhPost, submitJason, 30);
		LrhGetPost result = JacksonUtil.Json2Obj(resultJson, new TypeReference<LrhGetPost>() {
		});
		logger.info("lrh:" + lrhPost + "#" + JacksonUtil.Obj2Json(result));

		if (!(result.getStatus() == 1)) {
			rs.setCode(1);
			CustProductApply custProductApply = new CustProductApply();
			custProductApply.setAuditResult(0);
			custProductApply.setRejectMsg("决策失败");
			custProductApply.setIsApply(true);
			String dates = Utility.addSystemTimesByDay(30, "yyyy-MM-dd HH:mm:ss");
			custProductApply.setCreditApplyTime(dates);
			rs.setCustProductApply(custProductApply);

			// 发送失败短信
			try {
				String mobile = custAccount.getUserName();
				String appdesc = custAccount.getAppDesc();
				appdesc = appdesc.split(";")[0].toString();
				String productName = SmsDescEnum.getNameByAppDesc(appdesc);
				String userName = custAccount.getAccountRealname();
				sMSMessageManager.sendCreditFail(mobile, productName, userName);
			} catch (Exception e) {

			}
		} else {// 成功
			CustProductApply custProductApply = new CustProductApply();
			custProductApply.setAuditResult(1);
			custProductApply.setRejectMsg(result.getMessage());
			custProductApply.setCreditAmt((new BigDecimal(result.getApprovalAmount()).intValue()) * 100);// 额度
			custProductApply.setFormalitiesRate(new BigDecimal(result.getFormalitiesRate()));// 手续费率
			custProductApply.setInterestRateMonthly(new BigDecimal(result.getMonthRate()));// 月利率
			custProductApply.setServiceRate(new BigDecimal(result.getMonthServiceRate()));// 月服务费率
			custProductApply.setThirdPwd(pwdSubmit);
			rs.setCode(1);
			rs.setMsg("成功");
			rs.setCustProductApply(custProductApply);

			// 发送成功短信
			try {
				String mobile = custAccount.getUserName();
				String appdesc = custAccount.getAppDesc();
				appdesc = appdesc.split(";")[0].toString();
				String productName = SmsDescEnum.getNameByAppDesc(appdesc);
				String userName = custAccount.getAccountRealname();
				sMSMessageManager.sendCreditSuccess(mobile, productName, userName);
			} catch (Exception e) {

			}

		}
		return rs;
	}

	public static void main(String[] args) {
		System.out.println(new BigDecimal("6000.0").intValue());
	}

	/**
	 * 查询是否已经获取到了额度
	 * 
	 * @param mobile
	 * @param idcardNo
	 * @return
	 * @throws Exception
	 */
	@Log
	public ProductApplyResultVo searchApprovalAmount(String mobile, String idcardNo) throws Exception {

		ProductApplyResultVo rs = new ProductApplyResultVo();

		// 生成签名
		String sign = "";// 签名串
		TreeMap<String, String> parameterMap = new TreeMap<String, String>();
		parameterMap.put("caller", source);
		parameterMap.put("version", "1.0");
		parameterMap.put("appKey", appKey);
		parameterMap.put("userAccount", mobile);
		parameterMap.put("idcardNo", idcardNo);
		sign = createSign(appSecret, parameterMap);

		// 组装提交参数
		SearchAmount searchAmount = new SearchAmount();
		searchAmount.setCaller(source);
		searchAmount.setVersion(version);
		searchAmount.setAppKey(appKey);
		searchAmount.setSign(sign);
		searchAmount.setUserAccount(mobile);
		searchAmount.setIdcardNo(idcardNo);

		// lrh返回
		String submitJason = JacksonUtil.Obj2Json(searchAmount);
		logger.info("lrh:" + lrhSearch + "#" + submitJason);
		String resultJson = HttpRequest.doJson(url + lrhSearch, submitJason, 30);
		LrhGetPost result = JacksonUtil.Json2Obj(resultJson, new TypeReference<LrhGetPost>() {
		});
		logger.info("lrh:" + lrhSearch + "#" + JacksonUtil.Obj2Json(result));

		if (result.getStatus() == 1) {
			CustProductApply custProductApply = new CustProductApply();
			custProductApply.setAuditResult(1);
			custProductApply.setRejectMsg(result.getMessage());
			custProductApply.setCreditAmt(new BigDecimal(result.getApprovalAmount()).intValue() * 100);
			custProductApply.setFormalitiesRate(new BigDecimal(result.getFormalitiesRate()));// 手续费率
			custProductApply.setInterestRateMonthly(new BigDecimal(result.getMonthRate()));// 月利率
			custProductApply.setServiceRate(new BigDecimal(result.getMonthServiceRate()));// 月服务费率
			custProductApply.setIsApply(false);
			rs.setCode(1);
			rs.setMsg("成功");
			rs.setCustProductApply(custProductApply);
		} else {
			rs.setCode(0);
		}
		return rs;
	}

	/**
	 * 生成签名
	 * 
	 * @param appSecret
	 * @param parameterMap
	 * @return
	 * @throws Exception
	 */
	@Log
	public String createSign(String appSecret, TreeMap parameterMap) throws Exception {

		String sign = appSecret;
		Iterator<Map.Entry<String, String>> it = parameterMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			if (!((String) entry.getKey()).equals("sign")) {
				sign = sign + (String) entry.getKey() + (String) entry.getValue();
			}
		}
		sign = sign + appSecret;
		try {
			// MD5加密
			sign = md5Encode2UpperCase(sign);
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		return sign;
	}

	/**
	 * md5加密
	 * 
	 * @param sign
	 * @return
	 * @throws Exception
	 */
	@Log
	public static String md5Encode2UpperCase(String sign) throws Exception {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			logger.info(e.getMessage());
			return "";
		}
		byte[] byteArray = sign.getBytes("UTF-8");
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = md5Bytes[i] & 0xFF;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		String rs = hexValue.toString().toUpperCase();
		return rs;
	}

}
